/*
    This file is part of the substandard lisp implementation of Standard Lisp
    Copyright (C) 2011 Nicky Nickell

    substandard lisp is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function ballanced(input) {
  var tokens = [];
  var chan = new lisp_channel(input);
  while(true) {
    var t = chan.readtoken();
    if (t != EOFC) {
      tokens.push(t)
    } else {
      break
    }
  }
  var parens = 0;
  for (j in tokens) {
    switch (tokens[j]) {
    case '(':
      parens++;
      break;
    case ')':
      parens--;
      break;
    }
  }
  return parens == 0;
}

jQuery(function ($, undefined) {
  var lisp = new interpreter(new lisp_channel(), new lisp_channel(), new lisp_channel());
  lisp.initialize();
  var i = 1;
  var expression = '';
  $('#lisp_term').terminal(function (command, term) {
    expression += command;

    if (ballanced(expression)) {
      i++;
      term.set_prompt('[' + i + ']>');

      lisp.evaluate(expression);

      var out = lisp.stdout.flush();
      if (out != '') {
        term.echo(out);
      }
      out = lisp.stderr.flush();
      if (out != '') {
        term.error(out);
      }

      expression = '';
    } else {
      term.set_prompt('...    ');
    }
  }, {
    greetings: 'substandard lisp',
    name: 'terminal',
    height: '95%',
    width: '95%',
    prompt: '[1]>'
  });
});
